package com.atguigu.demojuc.chap07;

/**
 * @author njg
 * @version 1.0
 * @date 2025/6/17 20:47
 */

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 生产者消费者模式：使用阻塞队列实现该功能。
 * 一个生产者线程生产10个摸头
 * 一个消费者线程消费10个摸头
 * 馒头存放到阻塞队列中，容量3
 * <p>
 * 满了不能放，空了不能取
 */
public class ArrayBlockingQueueDemo {
    public static void main(String[] args) {
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);

        new Thread(() -> {

            for (int i = 1; i <= 10; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(2000);
                    blockingQueue.put(String.valueOf(i));
                    System.out.println(Thread.currentThread().getName() + "\t" + "生产的第" + i + "个馒头");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "生产者").start();

        new Thread(() -> {

            for (int i = 1; i <= 10; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(3000);
                    blockingQueue.take();
                    System.out.println(Thread.currentThread().getName() + "\t" + "消费的第" + i + "个馒头");

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "消费者·").start();
    }
}
